<template>
  <div class="main">
    <div class="top-container">
      <div class="left-section">
        <VanImage
            round
            width="4rem"
            height="4rem"
            :src="require('@/assets/backgrounds/user.jpg')"
        />
        <div class="info">
          <span class="title">{{ username }}</span>
          <Button round size="small" color="#323030" class="membership">
            <p class="membership-text">{{ membershipLevel }}</p>
          </Button>
        </div>
      </div>
      <div class="setting" @click="goToSetting">
          <Icon size="30" color="#808080" name="setting-o" />
      </div>
    </div>
    <div class="order-center" @click="goToOrderCenter">
      <Row>
        <Col span="24">
          <div class="my-order">
            <p class="order">我的订单</p>
            <div class="right-item">
              <p style="color:#FA6408;font-size: 13px">全部订单<Icon size="13" color="#808080" name="arrow" /></p>
            </div>
          </div>
        </Col>
      </Row>
      <van-grid :border="false" column-num="5">
        <van-grid-item icon="balance-list-o" text="待付款" style="color:#FA6408" @click="goToOrderCenter('待付款')" />
        <van-grid-item icon="send-gift-o" text="待发货" style="color:#FA6408" @click="goToOrderCenter('待发货')" />
        <van-grid-item icon="logistics" text="待收货" style="color:#FA6408" @click="goToOrderCenter('待收货')" />
        <van-grid-item icon="chat-o" text="待评价" style="color:#FA6408" @click="goToOrderCenter('待评价')" />
        <van-grid-item icon="after-sale" text="服务" style="color:#FA6408" @click="goToOrderCenter('售后')" />
      </van-grid>
    </div>
    <div class="common-tools">
      <Row>
        <Col span="24">
          <div class="my-order">
            <p class="order">常用工具</p>
          </div>
        </Col>
      </Row>
      <van-grid :border="false" column-num="4">
        <van-grid-item icon="vip-card-o" text="超级会员" @click="goToVIPView" />
        <van-grid-item icon="location-o" text="地址管理" @click="goToAddressManagement"/>
        <van-grid-item icon="clock-o" text="浏览记录" />
        <van-grid-item icon="comment-o" text="评价管理" @click="goToReviewsManagement"/>
      </van-grid>
    </div>
    <p class="like">— 猜你喜欢 —</p>
    <div class="show-image">
      <div class="masonry">
        <div class="card" v-for="product in displayedProducts" :key="product.productId">
          <div class="card-link" @click="handleClick(product.productId)">
            <VanImage class="product-image" :src="require('@/'+`${product.imageUrl}`)" />
            <p class="variety">{{ product.productName }}</p>
            <p class="introduction">{{ product.description }}</p>
            <p class="price-container">
              <span class="currency">¥  </span>
              <span class="price">{{ product.price }}</span>
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {Icon, Image as VanImage, Button, Row, Col, GridItem as VanGridItem, Grid as VanGrid, Toast} from "vant";
import http from "@/plugins/http";

export default {
  name: "MyView",
  components: { Icon, VanImage, Button, Row, Col, VanGrid, VanGridItem },
  data() {
    return {
      username: "",
      membershipLevel: "",
      products: [],
      displayedProducts: []
    };
  },
  methods: {
    handleClick(productId) {
      http.post(`/product/increment-click/${productId}`).then(res => {
            if (res.statusCode === '200' && res.data) {
              console.log("增加点击次数成功");
            }
      }).catch(error => {
        console.error("增加点击次数失败:", error);
      });
      this.$router.push({ name: 'PetView', params: { id: productId } });
    },

    fetchUserInfo() {
      const storedUser = JSON.parse(sessionStorage.getItem("username"));
      if (storedUser) {
        http.get(`/user/getUserInfo/${storedUser}`)
            .then(response => {
              const user = response.data;
              this.username = user.username;
              switch (user.userType) {
                case 1:
                  this.membershipLevel = "黄金会员";
                  break;
                case 2:
                  this.membershipLevel = "白金会员";
                  break;
                case 3:
                  this.membershipLevel = "钻石会员";
                  break;
                default:
                  this.membershipLevel = "普通会员";
              }
            })
            .catch(error => {
              console.error("获取用户信息出错:", error);
            });
      } else {
        console.error("没有用户登录");
      }
    },
    fetchProducts() {
      http.get("/product/all")
          .then(response => {
            this.products = response.data || [];
            this.displayedProducts = this.getRandomProducts(4);
          })
          .catch(error => {
            console.error("获取商品信息出错:", error);
          });
    },
    getRandomProducts(count) {
      if (!this.products || this.products.length === 0) return [];
      const shuffled = this.products.sort(() => 0.5 - Math.random());
      return shuffled.slice(0, count);
    },
    goToOrderCenter(active) {
      const storedUser = JSON.parse(sessionStorage.getItem("username"));
      if(storedUser) {
        this.$nextTick(() => {
          this.$router.push(`/OrderCenterView/${active}`).catch(err => {
            if (err.name !== 'NavigationDuplicated') {
              throw err;
            }
          });
        });
      }
      else
      {
        Toast.fail("请先登录");
        this.$router.push('/');
      }
    },
    goToAddressManagement() {
      const storedUser = JSON.parse(sessionStorage.getItem("username"));
      if(storedUser) {
        this.$router.push('/AddressView');
      } else
      {
        Toast.fail("请先登录");
        this.$router.push('/');
      }
    },
    goToReviewsManagement()
    {
      const storedUser = JSON.parse(sessionStorage.getItem("username"));
      if(storedUser) {
        this.$router.push('/MyReviewsView');
      } else
      {
        Toast.fail("请先登录");
        this.$router.push('/');
      }
    },
    goToSetting()
    {
      const storedUser = JSON.parse(sessionStorage.getItem("username"));
      if(storedUser) {
        this.$router.push('/SettingView');
      } else
      {
        Toast.fail("请先登录");
        this.$router.push('/');
      }
    },
    goToVIPView()
    {
      this.$router.push('VIPView');
    }
  },
  mounted() {
    this.fetchUserInfo();
    this.fetchProducts();
  }
};
</script>

<style scoped>
.main {
  background-color: #f6f7f9;
}
.top-container {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  background: linear-gradient(to bottom, #faeaea, #f6f7f9);
  padding: 15px 10px;
}
.left-section {
  display: flex;
  align-items: flex-end;
  margin-left: 10px;
  margin-bottom: 10px;
}
.info {
  display: flex;
  flex-direction: column;
  margin-left: 10px;
}
.membership {
  margin-top: 5px;
  height: 25px;
}
.membership-text {
  color: #ffc46c;
}
.setting {
  margin-right: 15px;
  display: flex;
  align-items: flex-end;
  margin-bottom: 20px;
}
.order-center {
  margin-left: 10px;
  margin-right: 10px;
  border-radius: 15px;
  background-color: #ffffff;
  overflow: hidden;
}
.my-order {
  margin-left: 15px;
  margin-top: 15px;
  margin-right: 15px;
  display: flex;
  justify-content: space-between;
}
.order {
  font-weight: bold;
  font-size: 15px;
}
.common-tools {
  margin-top: 10px;
  margin-left: 10px;
  margin-right: 10px;
  border-radius: 15px;
  background-color: #ffffff;
  overflow: hidden;
}
.like {
  margin-top: 20px;
  margin-bottom: 20px;
  text-align: center;
  font-weight: bold;
}
.masonry {
  column-count: 2;
  column-gap: 10px;
  padding-left: 10px;
  padding-right: 10px;
  padding-bottom: 80px;
}
.card {
  background-color: #ffffff;
  border-radius: 15px;
  box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  cursor: pointer;
  display: inline-block;
  margin-bottom: 10px;
  width: 100%;
}
.card-link {
  text-decoration: none;
  color: inherit;
}
.product-image {
  width: 100%;
  height: auto;
  display: block;
}
.variety {
  width: 100%;
  text-align: center;
}
.introduction {
  margin-top: 5px;
  color: #999987;
  font-size: 13px;
  padding-left: 13px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.price-container{
  margin-top: 5px;
  font-weight: bold;
  padding-left: 13px;
  margin-bottom: 10px;
}
.currency {
  color: #f85f0c;
  font-weight: bold;
  font-size: 20px;
}
.price {
  color: #f85f0c;
  font-weight: bold;
  font-size: 30px;
}
</style>
